// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import FastClick from "fastclick";
import VueRouter from "vue-router";
import App from "./App";
import router from "./router";
import VueResource from "vue-resource";
import { ToastPlugin, AlertPlugin, LoadingPlugin } from "vux";
import common from "../wechat/static/common/common";
import "babel-polyfill";
import Toast from "vue2-toast";
Vue.use(Toast);
Vue.use(ToastPlugin);
Vue.use(AlertPlugin);
Vue.use(LoadingPlugin);
Vue.use(VueResource);
FastClick.attach(document.body);
Vue.config.productionTip = false;

function intercept() {
  router.beforeEach((to, from, next) => {
    if (!common.getCookie("sessionId")) {
      let webUrl = window.location.href;
      if (webUrl.indexOf("code=") > 0) {
        let code = webUrl.split("code=")[1].split("&")[0];
        console.log(code);
        let url = "https://harmonygame.icebartech.com/api/html5/weiXinLogin",
          param = {
            code: code
          };
        Vue.http.post(url, param, { emulateJSON: true }).then(
          res => {
            let data = res.data;
            if (data.status == 200) {
              let sessionId = data.data.bussData.bussData.sessionId;
              common.setCookie("sessionId", sessionId);
              next();
            } else {
              console.log(data);
              console.log(data.msg);
            }
          },
          res => {
            console.log(res);
          }
        );
        return;
      }
      let test = "https://harmonygame.icebartech.com/";
      let online = window.location.href.includes("code")
          ? window.location.href.split("?")[0]
          : window.location.href,
        REDIRECT_URI = window.location.host == "localhost:8080" ? test : online,
        APPID = "wx97ff20a3efb35dec",
        SCOPE = "snsapi_userinfo",  
        STATE = "";
      location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${SCOPE}#wechat_redirect`;
    } else {
      next();
    }
  });

  Vue.http.interceptors.push(function(request, next) {
    //拦截器
    next(res => {
      //401 登陆过期跳转
      if (res.data.status == 401) {
        if (window.location.host.includes("8080")) return;
        common.setCookie("sessionId", "");
        location.reload();
      }
    });
  });

  Vue.config.productionTip = false;
}

intercept();
/* eslint-disable no-new */
new Vue({
  router,
  render: h => h(App)
}).$mount("#app-box");
